package org.example.service.Impl;

import lombok.AllArgsConstructor;
import org.example.dao.User;
import org.example.enums.responseEnum;
import org.example.mapper.UserMapper;
import org.example.service.UserService;
import org.example.util.MinioUtil;
import org.example.util.SaltMD5Util;
import org.example.util.VerifyUtil;
import org.springframework.stereotype.Service;

@AllArgsConstructor
@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

//    private final IpUtil ipUtil;

    private final MinioUtil minioUtil;

    @Override
    public User getUserById(User user) {
        User userByUsername = userMapper.getUserById(user);
        //如果头像存在的话就添加ip和端口
        if (userByUsername.getHeadImage() != null) {
            minioUtil.getUserHeadImageUrl(userByUsername);
        }
        return userByUsername;
    }

    @Override
    public User getUser(User user) {
        User userByUsername = userMapper.getUserByUsername(user);
        System.out.println(userByUsername.toString());
        //如果头像存在的话就添加ip和端口
        if (userByUsername.getHeadImage() != null) {
            minioUtil.getUserHeadImageUrl(userByUsername);
        }
        return userByUsername;
    }

    @Override
    public responseEnum login(User user) {
        User user1 = userMapper.getUserByUsername(user);
        if (user1 != null) {
            if (SaltMD5Util.verifySaltPassword(user.getPassword(), user1.getPassword())) {
                return responseEnum.success;
            } else {
                //密码错误
                return responseEnum.error;
            }
        } else {
            //该用户不存在
            return responseEnum.notFound;
        }
    }

    @Override
    public responseEnum register(User user) {
        User user1 = userMapper.getUserByUsername(user);
        //判断用户名是否存在
        if (user1 != null) {
            return responseEnum.notFound;
        }
        //判断用户名和密码是否符合规范
        if (!(VerifyUtil.validateUsername(user.getUsername()) && VerifyUtil.validatePassword(user.getPassword()))) {
            return responseEnum.error;
        }
        //给密码进行加密
        user.setPassword(SaltMD5Util.generateSaltPassword(user.getPassword()));
        //插入数据库
        Integer i = userMapper.register(user);
        if (i > 0) {
            return responseEnum.success;
        } else {
            return null;
        }
    }

    @Override
    public responseEnum updateUser(User user) {
        if (user.getId()==null){
            return responseEnum.notFound;
        }
        if (user.getUsername()!=null){
            User userByUsername = userMapper.getUserByUsername(user);
            if (userByUsername!=null){
                return responseEnum.error;
            }
        }
        Integer i = userMapper.updateUser(user);
        if (i > 0) {
            return responseEnum.success;
        }else {
            return responseEnum.error;
        }
    }


}
